import React, { useEffect, useMemo, useState } from "react";
import NavBar from "@/components/NavBar/NavBar";
import SearchBar from "@/components/SearchBar/SearchBar";
import CartItem from "@/components/CartItem/CartItem";
import { Button, Checkbox, Empty, Toast } from "antd-mobile";
import type { Cart as CartType } from "@/type/CartType";
import { changeCheckedAll, fetchCartListThunk } from "@/store/modules/cartStore";
import { useEnhanceDispatch, useEnhanceSelector } from "@/hooks";
import { SettleAccountsParams } from "@/type/OrderType";
import "./Cart.scss";
import { useNavigate } from "react-router-dom";


const Cart: React.FunctionComponent = () => {
   const enhanceDispatch = useEnhanceDispatch();

   const navigate = useNavigate();

   const token = useEnhanceSelector(state => state.loginStore.loginData).token;

   // 购物车商品列表
   const cartList: CartType[] = useEnhanceSelector(state => state.cartStore.cartList);
   // 是否全选
   const isCheckedAll: boolean = useMemo(() => cartList.every(item => item.checked), [cartList]);
   // 总价
   const toalPrice: number = useMemo(() => cartList.filter(item => item.checked).reduce((sum: number, item: CartType) => sum += item.goods_num * Number(item.goods.goods_price_max), 0), [cartList]);
   // 选中的购物车商品数量
   const checkedList: number = useMemo(() => cartList.filter(item => item.checked).reduce((sum, item) => sum += item.goods_num, 0), [cartList]);

   // 获取订单结算信息的参数
   const [params, setParams] = useState<SettleAccountsParams>({
      mode: "cart",
      cartIds: "",
      delivery: 10,
      couponId: 0,
      isUsePoints: 0,
   });
   /**
    * @description 获取购物车商品列表的回调函数
    * */
   const fetchCartList = async () => {
      if (!token) return Toast.show("当前没有登录");
      try {
         await enhanceDispatch(fetchCartListThunk()).unwrap();
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      }
   };

   /**
    * @description 全选和取消全选所有商品
    * */
   const handleCheckedAll = (checked: boolean) => {
      enhanceDispatch(changeCheckedAll());
   };

   const handlePay = async () => {
      const newParams: SettleAccountsParams = { ...params, cartIds: cartList.filter(item => item.checked).map(item => item.id).join() };
      setParams(params);
      navigate(`/checkout?mode=${newParams.mode}&cartIds=${newParams.cartIds}&delivery=${newParams.delivery}&couponId=${newParams.couponId}&isUsePoints=${newParams.isUsePoints}`);
   };

   const renderList = () => {
      if (cartList.length) {
         return (
            <>
               {
                  cartList.map((cart: CartType) => <CartItem good={cart} key={cart.goods_id}></CartItem>)
               }
            </>
         );
      } else {
         return (
            <div className="lazy-loading">
               <Empty description="暂无数据"></Empty>
            </div>
         );
      }
   };
   useEffect(() => {
      fetchCartList();
   }, []);

   return (
      <div className="cart-container">
         <div className="cart-header">
            <NavBar children="购物车"></NavBar>
            <SearchBar placeholder="搜索你要找的商品"></SearchBar>
         </div>
         <div className="cart-list">
            {
               renderList()
            }
         </div>
         {
            token && <div className="submit-bav">
               <div className="left">
                  <Checkbox checked={isCheckedAll && cartList.length !== 0} onChange={handleCheckedAll}>全选</Checkbox>
               </div>
               <div className="center">
                  <span className="total">合计</span>
                  <span className="price">￥{toalPrice}元</span>
               </div>
               <div className="right">
                  <Button color="primary" disabled={checkedList === 0} onClick={handlePay}>去结算({checkedList})</Button>
               </div>
            </div>
         }
      </div>
   );
};

export default Cart;
